package com.binhthuan.catechist.server.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.binhthuan.catechist.server.ErrorObject;
import com.binhthuan.catechist.server.ResponseObject;
import com.binhthuan.catechist.server.bus.CourseBUS;
import com.binhthuan.catechist.server.domain.Course;
import com.binhthuan.catechist.server.domain.Grade;
import com.binhthuan.catechist.server.domain.Shift;
import com.binhthuan.catechist.server.domain.Venue;
import com.binhthuan.catechist.server.domain.Year;
import com.binhthuan.catechist.shared.constant.Action;
import com.binhthuan.catechist.shared.constant.Parameter;

public class CourseServlet extends AbstractServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 4121314578522504195L;

    @Override
    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        addCourse(request, response);
    }

    @Override
    protected void fetch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (Action.GET_COURSES_BY_SCHOOL_YEAR.equals(request.getParameter(Parameter.OPERATION_INFO))) {
            getCoursesBySchoolYear(request, response);
        } else if (Action.GET_COURSES_BY_TRAINER.equals(request.getParameter(Parameter.OPERATION_INFO))) {
            getCoursesByTrainer(request, response);
        } else if (Action.GET_COURSES_BY_TRAINEE.equals(request.getParameter(Parameter.OPERATION_INFO))) {
            getCoursesByTrainee(request, response);
        } else if (request.getParameter(Parameter.ID) != null) {
            getCourseById(request, response);
        }
    }

    @Override
    protected void remove(HttpServletRequest request, HttpServletResponse response, boolean confirmation)
            throws ServletException, IOException {
        deleteCourse(request, response, confirmation);
    }

    @Override
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        updateCourse(request, response);
    }

    private void addCourse(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter(Parameter.CODE);
        String name = request.getParameter(Parameter.NAME);
        String gradeIdString = request.getParameter(Parameter.GRADE);
        String yearIdString = request.getParameter(Parameter.YEAR);
        String shiftIdString = request.getParameter(Parameter.SHIFT);
        String venueIdString = request.getParameter(Parameter.VENUE);

        try {
            CourseBUS bus = new CourseBUS();
            Course obj = bus.getCourseByCode(code.trim());
            if (obj != null) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.CODE, getMessagesFactory().duplicateCode());
                sendResponse(error.toJson());
                return;
            }

            obj = bus.getCourseByName(name.trim());
            if (obj != null) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().duplicateCode());
                sendResponse(error.toJson());
                return;
            }

            obj = new Course();
            obj.setCode(code);
            obj.setName(name);

            if (gradeIdString != null) {
                int gradeId = Integer.parseInt(gradeIdString);
                Grade grade = new Grade();
                grade.setId(gradeId);
                obj.setGrade(grade);
            }

            if (yearIdString != null) {
                int yearId = Integer.parseInt(yearIdString);
                Year year = new Year();
                year.setId(yearId);
                obj.setYear(year);
            }

            if (shiftIdString != null) {
                int shiftId = Integer.parseInt(shiftIdString);
                Shift shift = new Shift();
                shift.setId(shiftId);
                obj.setShift(shift);
            }

            if (venueIdString != null) {
                int venueId = Integer.parseInt(venueIdString);
                Venue venue = new Venue();
                venue.setId(venueId);
                obj.setVenue(venue);
            }

            if (bus.save(obj)) {
                sendResponse(new ResponseObject(obj).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void getCourseById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idString = request.getParameter(Parameter.ID);
        try {
            Integer id = (idString == null) ? null : Integer.parseInt(idString);

            CourseBUS bus = new CourseBUS();
            Course obj = bus.getCourseById(id);
            if (obj == null) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.ID, getMessagesFactory().itemNotFound(getConstantsFactory().course()));
                sendResponse(error.toJson());
                return;
            }

            sendResponse(new ResponseObject(obj).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void getCoursesByTrainer(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String trainerIdString = request.getParameter(Parameter.YEAR);
        try {
            Integer trainerId = (trainerIdString == null) ? null : Integer.parseInt(trainerIdString);

            CourseBUS bus = new CourseBUS();
            List<Course> obj = bus.getCoursesByTrainer(trainerId);

            sendResponse(new ResponseObject(obj).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void getCoursesByTrainee(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String traineeIdString = request.getParameter(Parameter.YEAR);
        try {
            Integer traineeId = (traineeIdString == null) ? null : Integer.parseInt(traineeIdString);

            CourseBUS bus = new CourseBUS();
            List<Course> obj = bus.getCoursesByTrainee(traineeId);

            sendResponse(new ResponseObject(obj).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void getCoursesBySchoolYear(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String yearIdString = request.getParameter(Parameter.YEAR);
        try {
            Integer yearId = (yearIdString == null) ? null : Integer.parseInt(yearIdString);

            CourseBUS bus = new CourseBUS();
            List<Course> obj = bus.getCoursesBySchoolYear(yearId);

            sendResponse(new ResponseObject(obj).toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }

    private void deleteCourse(HttpServletRequest request, HttpServletResponse response, boolean confirmation) {
        // TODO Auto-generated method stub

    }

    private void updateCourse(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idString = request.getParameter(Parameter.ID);
        String code = request.getParameter(Parameter.CODE);
        String name = request.getParameter(Parameter.NAME);
        String gradeIdString = request.getParameter(Parameter.GRADE);
        String yearIdString = request.getParameter(Parameter.YEAR);
        String shiftIdString = request.getParameter(Parameter.SHIFT);
        String venueIdString = request.getParameter(Parameter.VENUE);

        try {
            int id = Integer.parseInt(idString);

            CourseBUS bus = new CourseBUS();
            Course obj = bus.getCourseByCode(code.trim());
            if (obj != null && obj.getId() != id) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.CODE, getMessagesFactory().duplicateCode());
                sendResponse(error.toJson());
                return;
            }

            obj = bus.getCourseByName(name.trim());
            if (obj != null && obj.getId() != id) {
                ErrorObject error = new ErrorObject(STATUS_VALIDATION_ERROR);
                error.addError(Parameter.NAME, getMessagesFactory().duplicateCode());
                sendResponse(error.toJson());
                return;
            }

            obj = bus.getCourseById(id);
            if (obj == null) {
                return;
            }
            obj.setCode(code);
            obj.setName(name);

            if (gradeIdString != null) {
                int gradeId = Integer.parseInt(gradeIdString);
                Grade grade = new Grade();
                grade.setId(gradeId);
                obj.setGrade(grade);
            }

            if (yearIdString != null) {
                int yearId = Integer.parseInt(yearIdString);
                Year year = new Year();
                year.setId(yearId);
                obj.setYear(year);
            }

            if (shiftIdString != null) {
                int shiftId = Integer.parseInt(shiftIdString);
                Shift shift = new Shift();
                shift.setId(shiftId);
                obj.setShift(shift);
            }

            if (venueIdString != null) {
                int venueId = Integer.parseInt(venueIdString);
                Venue venue = new Venue();
                venue.setId(venueId);
                obj.setVenue(venue);
            }

            if (bus.save(obj)) {
                sendResponse(new ResponseObject(obj).toJson());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    }
}
